const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')
const rankfn = require('../lib/rankfn')
const Image = mongoose.model('Image')
const User = mongoose.model('User')
const Comment = mongoose.model('Comment')
const bcrypt = require('bcrypt')
const saltRounds = 10

router.get('/', async (ctx, next) => {
  console.log(ctx.session.username)
  ctx.session.user = 'abc'
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const newcomments = await Comment
  .find({})
  .sort({createdAt: -1})
  .limit(3)
  const stats = await statsfn()
  const ranks = await rankfn()
  await ctx.render('index', {
    title: '图片分享',
    images, stats, ranks, username: ctx.session.username, newcomments
  })
})

router.get('/login', async ctx => {
  await ctx.render('login', {})
})

router.post('/login', async ctx => {
  const {username, password} = ctx.request.body
  let loginsuc = false
  let user
  if(username.length>=3) {
    console.log(username)
    user = await User.find({username: username})
    
    if(user!=null && user.length != 0) {
      if(username === user[0].username && bcrypt.compareSync(password, user[0].password)) {
        loginsuc = true
      }
    }
    
  }
  
  if(loginsuc) {
    ctx.session.username = username
    ctx.redirect('/?loginsuc=true')
  } else {
    ctx.redirect('/login?loginsuc=false')
  }
  
})

router.get('/logout', async ctx => {
  ctx.session.username = undefined
  ctx.redirect('/')
})

router.get('/register', async ctx => {
  await ctx.render('register', {})
})

router.post('/register', async ctx => {
  const {username, password} = ctx.request.body
  let registersuc = false
  let ifuser
  if(username.length >= 3) {
    ifuser = await User.find({username: username})
    if((!(ifuser !== null) || ifuser.length === 0) && username.length >= 3 && password.length >= 6) {
      registersuc = true
    }
  }
  if(registersuc === true) {
    var salt = bcrypt.genSaltSync(saltRounds)
    var hash = bcrypt.hashSync(password, salt)
    await User.create({
      username, password: hash, salt
    })
    // bcrypt.genSalt(saltRounds, function(err, salt) {
    //   bcrypt.hash(password, salt, async function(err, hash) {
    //     console.log(salt + "*****\n" + hash)
    //     await User.create({
    //       username, password: hash, salt
    //     })
    //   });
    // });
    ctx.redirect('/login?registersuc=true')
  } else {
    ctx.redirect('/register?registersuc=false')
  }
})

module.exports = router
